package cn.edu.neusoft.maxingxin231.yuejian06.Model;

import java.util.List;

import cn.edu.neusoft.maxingxin231.yuejian06.Bean.PostBean;
import cn.edu.neusoft.maxingxin231.yuejian06.Listener.ListListener;
import cn.edu.neusoft.maxingxin231.yuejian06.Listener.LoginListener;
import cn.edu.neusoft.maxingxin231.yuejian06.Service.LoginService;
import cn.edu.neusoft.maxingxin231.yuejian06.Service.Server;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 吴皓 on 2017/11/8.
 */

public class RetrofitBaseModel {
    private LoginService loginService;
    private Retrofit retrofit;
    public Retrofit getRetrofit(){
        retrofit=new Retrofit.Builder()
                .baseUrl(Server.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }
    public LoginService getLoginService(){
        loginService=retrofit.create(LoginService.class);
        return loginService;
    }
    public <T> void callenqueue(Call<T> call, final LoginListener<T> loginListener){
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.isSuccessful()&&response.body()!=null){
                    loginListener.onResponse(response.body());
                }
                else {
                    loginListener.onFail("error");
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {

                loginListener.onFail("error");
            }
        });
    }

    public <T> void callenqueueList(
            Call<List<T>> call,
            final ListListener<T> listListener){
        call.enqueue(new Callback<List<T>>() {
            @Override
            public void onResponse(Call<List<T>> call, Response<List<T>> response) {
                if (response.isSuccessful()&&response.body()!=null){
                    listListener.onResponse(response.body());
                }
                else {
                    listListener.onFail("error");
                }
            }

            @Override
            public void onFailure(Call<List<T>> call, Throwable t) {
                listListener.onFail("error");
            }
        });
    }


}
